package com.union.vehicleassistant.module.service;

import android.app.Service;
import android.bluetooth.BluetoothGatt;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.BusUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.union.vehicleassistant.common.Constant;
import com.union.vehicleassistant.util.BlueToothUtil;
import com.union.vehicleassistant.util.RxTimer;
import com.union.vehicleassistant.util.SettingUtils;

import java.util.Objects;

public class BindBleService extends Service {

    private BleDevice connectedDevice;
    private final RxTimer timer = new RxTimer();

    public static class BleBinder extends Binder {
        private BindBleService service;

        public BleBinder() {
        }

        public BleBinder(BindBleService service) {
            this.service = service;
        }

        public void connectBle() {
            service.connectBlueTooth();
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        connectBlueTooth();
        return new BleBinder(this);
    }

    private void startListen(String mac) {
        timer.interval(1000, number -> {
            boolean connected = BleManager.getInstance().isConnected(mac);
            if (!connected) {
                BusUtils.post(Constant.BUS_KEY_BLE_DISCONNECT);
                timer.cancel();
            }
        });
    }

    /**
     * 链接蓝牙
     */
    private void connectBlueTooth() {
        String mac = SettingUtils.getInstance().getConnectBluetoothMac();
        if (TextUtils.isEmpty(mac)) {
            BusUtils.post(Constant.BUS_KEY_BLE_NO_BLE);
            return;
        }

        if (BleManager.getInstance().isConnected(mac)) {
            BleDevice device = BlueToothUtil.getBleDevice(mac);
            BusUtils.post(Constant.BUS_KEY_BLE_SUCCESS, Objects.requireNonNull(device));
            return;
        }

        BleManager.getInstance().connect(mac, new BleGattCallback() {
            @Override
            public void onStartConnect() {

            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                BusUtils.post(Constant.BUS_KEY_BLE_FAIL);
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                connectedDevice = bleDevice;
                SettingUtils.getInstance().setConnectBleMac(bleDevice.getMac());
                BusUtils.post(Constant.BUS_KEY_BLE_SUCCESS, bleDevice);
                startListen(bleDevice.getMac());
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
//                BusUtils.post(Constant.BUS_KEY_BLE_DISCONNECT);
            }
        });
    }

    @Override
    public boolean onUnbind(Intent intent) {
        timer.cancel();
        releaseBle();
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        releaseBle();
        super.onDestroy();
    }

    private void releaseBle() {
        if (null != connectedDevice) {
            boolean connected = BleManager.getInstance().isConnected(connectedDevice);
            if (connected) {
                BleManager.getInstance().disconnect(connectedDevice);
            }
        }
    }
}
